package com.stone.serverless.sdk.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.stone.serverless.sdk.constant.ClassPathConstant;
import com.stone.serverless.sdk.loader.JarLoadService;
import com.stone.serverless.sdk.loader.ModuleClassLoader;

import java.lang.reflect.Method;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/14 13:56
 * @Version: 1.0.0
 */
public class ComponentVirtualInvocationHandler extends ComponentInvocationHandler {
    private String componentName;

    private String version;

    private String classPath;

    public ComponentVirtualInvocationHandler(String componentName, String version, String classPath) {
        super(null);
        this.componentName = componentName;
        this.version = version;
        this.classPath = classPath;
    }


    @Override
    public Object proxy(Object proxy, Method method, Object[] args, Object target) throws Throwable {
        ClassLoader classLoader = this.getClass().getClassLoader();
        Class<?> superclass = classLoader.getClass().getSuperclass();
        if (null == superclass) {
            return null;
        }
        Class<?>[] interfaces = superclass.getInterfaces();
        if (null == interfaces || interfaces.length == 0) {
            return null;
        }
        if (interfaces[0].getName().equals(ModuleClassLoader.class.getName())) {
            Object jarLoadService = ReflectUtil.getFieldValue(classLoader, "jarLoadService");
            Class<?> aClass = classLoader.loadClass(ClassPathConstant.RESOLVE_SERVICE_CLASS_PATH);
            Method me = ReflectUtil.getMethod(aClass, "getDependOutServiceByComponentInfo", String.class, String.class,
                    String.class, jarLoadService.getClass());
            Object getOutService = ReflectUtil.invokeStatic(me, classPath, componentName,
                    version, jarLoadService);

            if (ObjectUtil.isNull(getOutService)) {
                if (componentName.equals("system")) {
                    if (classPath.equals(JarLoadService.class.getName())) {
                        getOutService = jarLoadService;
                    }
                }
            }
            if (ObjectUtil.isNull(getOutService)) {
                System.out.println("找不到 外部服务提供者 " + classPath);

                return null;
            }
            return super.proxy(proxy, method, args, getOutService);
        }
        return null;
    }

}
